<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org" xmlns:display="http://www.w3.org/1999/xhtml">
<div th:replace="common/common::html"></div>
<head>
    <meta charset="UTF-8">
    <title th:text="#{login.title}"></title>

    <script th:inline="javascript">
        /**
         * 文件类型
         * @type {number}
         */
        const TYPE_FILE = 0;
        /**
         * 文件夹
         * @type {number}
         */
        const TYPE_FOLDER = 1;

        /**
         * 文件大小:GB
         * @type {number}
         */
        const SIZE_GB = 1024*1024*1024;

        /**
         * 文件大小:MB
         * @type {number}
         */
        const SIZE_MB = 1024*1024;

        /**
         * 文件大小:KB
         * @type {number}
         */
        const SIZE_KB = 1024;

        var _gridWidth;
        var _gridHeight;

        var _regJpg = new RegExp("^.*((jpg)|(png)|(jpeg))$")
        var _regAudio =  new RegExp("^.*((mp3))$")
        var _regVedio =  new RegExp("^.*((mp4))$")
        //页面自适应
        function resizePageSize() {
            _gridWidth = $(document).width() - 12;
            _gridHeight = $(document).height() - 110;
        }

        $(function () {
            resizePageSize()
            var _columnWidth = (_gridWidth-150)/6;
            $("#flexigrid-id").flexigrid({
                width : _gridWidth,
                height : _gridHeight,
                url : /*[[@{/file/queryFileListByPage}]]*/"",
                dataType : 'json',
                colModel : [

                    {display : 'fileUuid',name : 'fileUuid',width : 150,sortable : false,align : 'center',hide : 'true'},
                    {display : /*[[#{file.name}]]*/"",name : 'fileName',width : _columnWidth, sortable : true,align : 'center',
                        process:function (v,trid,rowData){
                            var htmlContents = ''
                            if(rowData.fileType === TYPE_FOLDER){
                                htmlContents+=`<a href="#" class="folder-type" onclick="enterDir('${rowData.fileUuid}','${rowData.filePath}')"><i class="glyphicon glyphicon-folder-open"></i><span>${v}</span></a>`
                            }else {

                                if(_regJpg.test(v)){
                                    htmlContents+=`<a href="#" class="file-type" onclick="preImg('${rowData.fileUuid}','${v}')"><i class="glyphicon glyphicon-picture"></i><span>${v}</span></a>`
                                }else if(_regAudio.test(v)){
                                    htmlContents+=`<a href="#" class="file-type" ><i class="glyphicon glyphicon-music"></i><span>${v}</span></a>`
                                }
                                else if(_regVedio.test(v)){
                                    htmlContents+=`<a href="#" class="file-type" ><i class="glyphicon glyphicon-facetime-video"></i><span>${v}</span></a>`
                                }
                                else{
                                    htmlContents+=`<a href="#" class="file-type" ><i class="glyphicon glyphicon-file"></i><span>${v}</span></a>`
                                }

                            }
                            return htmlContents;
                        }},
                    {display : /*[[#{file.size}]]*/"",name : 'fileCapacity',width : _columnWidth, sortable : true,align : 'center',
                        process:function (v,trid,rowData){
                            if(v === 0){
                                htmlContents='--';
                            }
                            else if(v > SIZE_GB){
                                htmlContents = (v/SIZE_GB).toFixed(2) + "GB";
                            }
                            else if(v > SIZE_MB){
                                htmlContents = (v/SIZE_MB).toFixed(2) + "MB";
                            }
                            else if(v > SIZE_KB){
                                htmlContents = (v/SIZE_KB).toFixed(2) + "KB";
                            }

                            else
                            {
                                htmlContents=v +'B';
                            }
                            return htmlContents;
                        }},
                    {display : /*[[#{file.type}]]*/"",name : 'fileType',width : _columnWidth, sortable : true,align : 'center',
                        process:function (v,trid,rowData){
                            var htmlContents = ''
                            if(v === TYPE_FOLDER){
                                htmlContents=/*[[#{file.type.folder}]]*/'';
                            }else{
                                htmlContents=/*[[#{file.type.file}]]*/'';
                            }
                            return htmlContents;
                        }},
                    {display : /*[[#{main.nice.name}]]*/"",name : 'niceName',width : _columnWidth, sortable : false,align : 'center'},
                    {display : /*[[#{modify.time}]]*/"",name : 'modtime',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{common.operation}]]*/"",name : 'fileUuid',width : _columnWidth, sortable : false,align : 'center',
                        process:function (v,trid,rowData) {
                            var htmlContents = ''
                            if(rowData.fileType === TYPE_FILE){
                                htmlContents+=`<section class="table-operation">`
                                htmlContents+=`<a href="downloadFile/${v}" target="_blank" class="folder-type" title=[[#{file.download}]]""><i class="glyphicon glyphicon-cloud-download"></i></a>`
                                htmlContents+=`<a href="#" class="file-type" title=[[#{file.share.title}]]"" onclick="shareFile('${v}','${rowData.fileName}')"><i class="glyphicon glyphicon-send"></i></a>`
                                htmlContents+=`</section>`
                            }else {
                                htmlContents+="--"
                            }

                            return htmlContents;
                        }}
                ],
                resizable : false, //resizable table是否可伸缩
                useRp : true,
                usepager : true, //是否分页
                autoload : false, //自动加载，即第一次发起ajax请求
                hideOnSubmit : true, //是否在回调时显示遮盖
                showcheckbox : true, //是否显示多选框
                rowhandler : rowDbclick, //是否启用行的扩展事情功能,在生成行时绑定事件，如双击，右键等
                rowbinddata : true
            });
            query();

            //创建文件夹对话框
            $("#mkdir-dialog-id").dialog({
                autoOpen : false,
                width : 600,
                modal : true,
                resizable : false,
                title: /*[[#{file.mkdir.dialog}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function () {
                            var flag=$("#folder-name-id").checkDom()
                            if (!flag){
                                return
                            }
                            $.ajax({
                                type: 'post',
                                async: false,
                                dataType : 'json',
                                url: /*[[@{/file/mkdir}]]*/'',
                                data: [
                                    {name:"folderName",value: $("#folder-name-id").val()},
                                    {name:"parentName",value: $("#file-folder-id").val()},
                                ],
                                success: function (data) {
                                    if (data && data.success){
                                        $("#mkdir-dialog-id").dialog('close')
                                        query()
                                    }else{
                                        message(data.msg)
                                    }

                                },
                                error: function(msg){
                                    message(/*[[#{common.error}]]*/'');
                                }

                            });
                        }
                    },
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }
                ]
            });
            //上传文件对话框
            $("#upload-dialog-id").dialog({
                autoOpen : false,
                width : 600,
                modal : true,
                resizable : false,
                title: /*[[#{file.upload.dialog}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function () {
                            var flag=$("#upload-form-id input.form-control").checkDom()
                            if (!flag){
                                return
                            }
                            $("#upload-form-id").submit()

                        }
                    },
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }
                ]
            })
            //上传文件表单
            $("#upload-form-id").ajaxForm({
                dataType: "json",
                success : function(data) {
                    if(data.success){
                        $("#upload-dialog-id").dialog('close')
                        query();
                    }else {
                        message(data.msg)
                    }
                },
                error : function() {
                    message(/*[[#{common.error}]]*/'');
                }
            })
            //分享文件对话框
            $("#share-file-dialog-id").dialog({  autoOpen : false,
                width : 600,
                modal : true,
                resizable : false,
                title: /*[[#{file.upload.dialog}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function () {
                            //TODO

                        }
                    },
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }
                ]
            })
            $("#pre-img-dialog-id").dialog({
                autoOpen : false,
                width : 600,
                modal : true,
                resizable : false,
                title: /*[[#{file.upload.dialog}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }
                ]
            })
            // 添加回车事件监听
            $(document).ready(function() {
                $("#search-keyword").keypress(function(e) {
                    if (e.which == 13) { // 回车键
                        searchFiles();
                        return false;
                    }
                });
            });

        });//ready
        //双击事件
        function rowDbclick(r) {
            $(r).dblclick(function () {
                var columnArray = $(r).attr('ch').split('_FG$SP_');
                //TODO
            });

        }
        function query() {
            var fileUuid = $("#file-folder-id").attr('file-uuid');
            var searchKeyword = $("#search-keyword").val(); // 获取搜索关键词

            $("#flexigrid-id").flexOptions({
                extParam: [
                    { name: "fileUuid", value: fileUuid },
                    { name: "fileNameLike", value: searchKeyword } // 添加搜索参数
                ]
            }).flexReload();
        }

        // 新增搜索函数
        function searchFiles() {
            query(); // 直接调用现有的查询函数
        }

        function synchData() {
            $.ajax({
                type: 'post',
                async: false,
                dataType : 'json',
                url: /*[[@{/file/synchFileData}]]*/'',
                data: [],
                success: function (data) {
                    query()
                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }

            });
        }
        //进入子目录
        function enterDir(fileUuid,filePath) {
            $("#file-folder-id").attr('file-uuid',fileUuid)
            $("#file-folder-id").val(filePath)
            query()
        }
        //进入上一级目录
        function enterLevelUp() {
            var fileUuid = $("#file-folder-id").attr('file-uuid')
            $.ajax({
                type: 'post',
                async: false,
                dataType : 'json',
                url: /*[[@{/file/queryParentFileById}]]*/'',
                data: [
                    {name:"fileUuid",value: fileUuid}
                ],
                success: function (data) {
                    if (data){
                        enterDir(data.fileUuid,data.filePath)
                    }else{
                        enterDir("-1","/")

                    }

                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }

            });
        }
        //创建文件夹
        function mkdir() {
            $("#folder-name-id").val('')
            $("#mkdir-dialog-id").dialog("open")
        }

        //上传文件
        function uploadFile() {
            $("#upload-form-id").resetForm()
            var parentPath =  $("#file-folder-id").val()
            $("#upload-parent-path").val(parentPath)
            $("#upload-dialog-id").dialog("open")

        }
        //分享文件
        function shareFile(fileUuid,fileName) {
            //alert(fileUuid + "|" + fileName)
            $("#share-name-id").text(fileName)
            $("#share-file-dialog-id").attr("file-uuid",fileUuid)
            queryShareUrl()
            $("#share-file-dialog-id").dialog('open')

        }
        //查询分享文件地址
        function queryShareUrl() {
            var fileUuid = $("#share-file-dialog-id").attr("file-uuid")
            var shareDate = $("#share-date-id").val()
            $.ajax({
                type: 'post',
                async: false,
                dataType : 'json',
                url: /*[[@{/file/queryShareUrl}]]*/'',
                data: [
                    {name:"fileUuid",value: fileUuid},
                    {name:"shareDate",value: shareDate}
                ],
                success: function (data) {
                    if(data){
                        $("#share-url-id").val(data.code)
                    }
                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }

            });

        }
        //复制链接
        function copyShareUrl(){
            $("#share-url-id").focus();
            $("#share-url-id").select();
            document.execCommand("Copy"); // 执行浏览器复制命令
        }
        //预览图片
        function preImg(fileUuid,fileName) {
            $.ajax({
                type: 'post',
                async: false,
                dataType : 'json',
                url: /*[[@{/file/queryFileUrl}]]*/'',
                data: [
                    {name:"fileUuid",value: fileUuid}
                ],
                success: function (data) {
                    if(data){
                        //data.code
                        $("#pre-img-id").attr("src",data.code)
                        $("#pre-img-dialog-id").dialog('option',"title",fileName);
                        $("#pre-img-dialog-id").dialog('open')
                    }
                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }

            });
        }
        //复制文件
        function copyFile() {
            var fileTypes = $("#flexigrid-id").getFlexigridiAttrByIndex(2)
            if(fileTypes.length === 0){
                message(/*[[#{common.select.one}]]*/'')
                return;
            }
            var flag = true
            $(fileTypes).each(function (index,item) {
                if(item === TYPE_FOLDER.toString()){
                    flag = false;
                }
            })

            if(!flag){
                message(/*[[#{flie.only.select.file}]]*/'')
                return;
            }

            var fileUuidArray = $("#flexigrid-id").getFlexigridiAttrByIndex(0)
            $("#copy-paste-id").attr("file-uuid-array",fileUuidArray)
            $("#copy-paste-id").attr("src-dir",$("#file-folder-id").val())
            $("#copy-paste-id").css('display','block')
            $("#copy-paste-num-id").text(fileTypes.length)
        }
        //取消复制文件
        function cancelCopy() {

            $("#copy-paste-id").css('display','none')
            $("#copy-paste-num-id").text(0)
        }
        //粘贴文件
        function copyPaste() {
            var srcDir = $("#copy-paste-id").attr('src-dir')
            var descDir = $("#file-folder-id").val();
            if(srcDir === descDir){
                message(/*[[#{file.select.no.same.folder}]]*/)
                return
            }

            var fileUuidArray = $("#copy-paste-id").attr("file-uuid-array")
            $.ajax({
                type: 'post',
                async: false,
                dataType : 'json',
                url: /*[[@{/file/copyPasteFile}]]*/'',
                data: [
                    {name:"fileUuidArray",value: fileUuidArray},
                    {name:"descDir",value: descDir}
                ],
                success: function (data) {
                    query()
                    cancelCopy()
                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }

            });
        }

    </script>
    <style>
        header{
            display: flex;
            align-items: center;
            height: 44px;
        }

        header > nav,
        header > a{
            margin-right: 10px;
        }
        nav{
            padding:0 10px;
            border-left:1px solid #2f332a;
            border-right:1px solid #2f332a
        }
        .folder-type,
        .file-type{
            display: flex;
            justify-content: space-around;
            width: 100%;
        }
        .folder-type > i,
        .folder-type > span
        {
            color: #d58512;
        }
        .file-type > i,
        .file-type > span{
            color: #80a5d5;
        }

        .table-operation{
            display:flex;
            width:100%;
            justify-content: center;
        }
        .tb-tr{
            display:flex;
            justify-content: space-between;
            margin-bottom: 5px;
        }
        .tb-tr >.form-control{
            display: inline-block;
            width: 80%;
        }

        header {
            display: flex;
            align-items: center;
            height: 44px;
            gap: 10px;
            padding: 0 10px;
        }

        /* 搜索容器调整 */
        .search-container {
            display: flex;
            align-items: center;
            flex-shrink: 0;
        }
    </style>


</head>
<body>
<header>
    <nav >
        <a href="#" th:title="#{file.level.up}">
            <i class="glyphicon glyphicon-level-up" onclick="enterLevelUp()"></i>
        </a>
        <input id="file-folder-id" file-uuid="-1" value="/" readonly>
    </nav>

    <a href="#" th:title="#{file.synch.data}">
        <i class="glyphicon glyphicon-refresh" onclick="synchData()"></i>
    </a>

    <a href="#" th:title="#{file.mkdir}">
        <i class="fa fa-folder" onclick="mkdir()"></i>
    </a>
    <a href="#" th:title="#{file.upload}">
        <i class="glyphicon glyphicon-cloud-upload" onclick="uploadFile()"></i>
    </a>

    </a>
    <a href="#" th:title="#{common.copy}" onclick="copyFile()">
        <i class="glyphicon glyphicon-duplicate"></i>
    </a>

    </a>
    <a id="copy-paste-id" href="#" style="border: 1px #000 solid;display: none" src-dir="" file-uuid-array="">
        <i class="glyphicon glyphicon-paste" style="padding: 3px" onclick="copyPaste()"></i>
        <span th:text="#{common.paste}" onclick="copyPaste()"></span>
        <span>(</span>
        <span id="copy-paste-num-id">10</span>
        <span>)</span>
        <i class="glyphicon glyphicon-remove" style="color: #f00;border-left: 1px #000 solid;padding: 3px" onclick="cancelCopy()"></i>
    </a>

    <!-- 新增搜索框 -->
    <div class="search-container">
        <input type="text" id="search-keyword" class="form-control"
               placeholder="输入文件名搜索" style="width: 200px; margin-right:5px">
        <a href="#" class="btn btn-primary" onclick="searchFiles()">
            <i class="glyphicon glyphicon-search"></i>
        </a>
    </div>
</header>
<table id="flexigrid-id"></table>
<div id="mkdir-dialog-id" style="display: none">
    <div class="form-group">
        <span th:text="#{file.type.folder.name}"></span>
        <input class="form-control" id="folder-name-id" pattern="^.+$">
    </div>
</div>

<div id="upload-dialog-id" style="display: none">
    <form id="upload-form-id" method="post" enctype="multipart/form-data" action="uploadFile">
        <input name="parentPath" id="upload-parent-path" type="hidden">
        <div class="form-group">
            <span th:text="#{file.name}"></span>
            <input  type="file" class="form-control" name="fileName" pattern="^.+$">
        </div>
    </form>

</div>
<div id="share-file-dialog-id" style="display:none">
    <div class="tb-tr">
        <span th:text="#{file.share.name}"></span>
        <span class="form-control" id="share-name-id"></span>
    </div>

    <div class="tb-tr">
        <span th:text="#{file.share.date}"></span>
        <input class="form-control" id="share-date-id" type="number" value="1" onchange="queryShareUrl()" ></input>
    </div>

    <div class="tb-tr">
    <span th:text="#{file.share.link}"></span>
    <div style="width: 80%; display:flex;flex-direction:column">
        <textarea class="form-control" id="share-url-id" type="number" value="1" style="height: 100px"></textarea>
        <a href="#" th:text="#{file.share.copy.link}" onclick="copyShareUrl"></a>
    </div>

    </div>
</div>
<div id="pre-img-dialog-id">
    <img id="pre-img-id" style="height: 400px">
</div>




</body>
</html>